import { getSession } from '@/lib/auth';
import env from '@/lib/env';
import redis, { genCosTokenKey } from '@/lib/redis';
import STS from 'qcloud-cos-sts';

const getPolicy = (userId: string) => ({
  version: '2.0',
  statement: [
    {
      action: [
        // 简单上传
        'name/cos:PutObject',
        'name/cos:PostObject',
        // 分片上传
        'name/cos:InitiateMultipartUpload',
        'name/cos:ListMultipartUploads',
        'name/cos:ListParts',
        'name/cos:UploadPart',
        'name/cos:CompleteMultipartUpload',
        // 删除
        'name/cos:DeleteObject',
      ],
      resource: [
        `qcs::cos:${env.COS_REGION}:uid/${env.COS_APPID}:${env.COS_BUCKET}/${userId}/*`,
        `qcs::cos:${env.COS_REGION}:uid/${env.COS_APPID}:${env.COS_BUCKET}/common/*`,
      ],
    },
    {
      // 下载
      action: ['name/cos:GetObject'],
      resource: [
        `qcs::cos:${env.COS_REGION}:uid/${env.COS_APPID}:${env.COS_BUCKET}/*`,
      ],
    },
  ],
});

export async function GET() {
  try {
    const session = await getSession();
    if (!session) throw new Error('用户未登录');
    const cacheToken = await redis.get(genCosTokenKey(session.user.id));
    if (cacheToken) return new Response(cacheToken);
    const res = new Promise<STS.CredentialData>((resolve, reject) => {
      STS.getCredential(
        {
          secretId: env.COS_SECRET_ID,
          secretKey: env.COS_SECRET_KEY,
          durationSeconds: 600,
          policy: getPolicy(session.user.id),
        },
        (err, credential) => (err ? reject(err) : resolve(credential)),
      );
    });
    const credential = await res;
    const data = JSON.stringify(credential);
    await redis.setEx(genCosTokenKey(session.user.id), 600, data);
    return new Response(data);
  } catch (error: any) {
    console.error(error);
    return new Response(error.message ?? 'internal server error');
  }
}
